package com.github.shiqiyue.myadmin.config.session;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.session.web.http.CookieHttpSessionIdResolver;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

/****
 * httpSession策略，同时支持cookie和header
 *
 * @author wwy
 *
 */
public class CookieAndHeaderHttpSessionIdResolver implements HttpSessionIdResolver {
	
	private CookieHttpSessionIdResolver cookieHttpSessionIdResolver = new CookieHttpSessionIdResolver();
	
	private HeaderHttpSessionIdResolver headerHttpSessionIdResolver = HeaderHttpSessionIdResolver.xAuthToken();
	
	private static final String SESSION_REQUEST_PARAM = "x-auth-token";
	
	@Override
	public List<String> resolveSessionIds(HttpServletRequest request) {
		// header part
		List<String> sessionIds = headerHttpSessionIdResolver.resolveSessionIds(request);
		if (sessionIds != null && !sessionIds.isEmpty()) {
			return sessionIds;
		}
		// cookie part
		sessionIds = getCookieHttpSessionIdResolver().resolveSessionIds(request);
		if (sessionIds != null && !sessionIds.isEmpty()) {
			return sessionIds;
		}
		// 从请求参数获取sessionId
		String sessionId = request.getParameter(SESSION_REQUEST_PARAM);
		return Arrays.asList(sessionId);
	}
	
	@Override
	public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
		headerHttpSessionIdResolver.setSessionId(request, response, sessionId);
		getCookieHttpSessionIdResolver().setSessionId(request, response, sessionId);
	}
	
	@Override
	public void expireSession(HttpServletRequest request, HttpServletResponse response) {
		headerHttpSessionIdResolver.expireSession(request, response);
		getCookieHttpSessionIdResolver().expireSession(request, response);
	}
	
	public CookieHttpSessionIdResolver getCookieHttpSessionIdResolver() {
		return cookieHttpSessionIdResolver;
	}
	
}
